#!/usr/bin/python
# coding:utf-8

from flask import request
from flask_restplus import Namespace, Resource, fields
from dao import userdao

ns = Namespace('users', description='用户管理相关API')

user = ns.model('User', {
    'id': fields.Integer(),
    'gid': fields.String(required=True),
    'name': fields.String(required=True),
    'status': fields.Integer()
})


@ns.route('/')
class CatList(Resource):
    @ns.doc(description='获取用户列表')
    @ns.marshal_list_with(user)
    def get(self):
        array = userdao.read_list()
        if len(array) == 0:
            array = []
        return array

    @ns.doc(description='添加新的用户')
    @ns.expect(user)
    @ns.marshal_with(user, code=201)
    def post(self):
        result = userdao.create(request.json)
        if result is None:
            ns.abort(400)
        return result, 201


@ns.route('/<gid>', endpoint='user')
class User(Resource):

    @ns.doc(description='获取某具体用户的详细信息')
    @ns.marshal_with(user)
    def get(self, gid):
        result = userdao.read(gid)
        if result is None:
            ns.abort(404, 'Not found the user of %s' % gid)
        return result

    @ns.doc(description='修改用户信息')
    @ns.marshal_with(user)
    @ns.expect(user, validate=True)
    def put(self, gid):
        result = userdao.update(gid, request.json)
        if result is None:
            ns.abort(404, 'Not found the user of %s' % gid)
        return result

    @ns.doc(description='删除用户')
    @ns.marshal_with(None)
    def delete(self, gid):
        userdao.delete(gid)
